/**
 * @description 用户选择器(根据用户roleType选择)
 */
var UserTypeSelector = {

	/**
	 * callbackOrConf 回调函数或配置选项，若为map类型，则表示为配置选项 isSingle 是否单选
	 */
	getView : function(callbackOrConf, isSingle, roleType, selval) {
		// 单选
		if (typeof(callbackOrConf) == 'object') {
			this.scope = callbackOrConf.scope || this;
			this.callback = callbackOrConf.callback;
		} else {
			this.scope = this;
			this.callback = callbackOrConf;
		}
		this.isSingle = (isSingle != null) ? isSingle : true;
		this.roleType = roleType || '0';		

		var panel = this.initPanel(isSingle, selval);

		this.win = new Ext.Window({
					//id : 'UserTypeSelectorWin',
					title : '选择用户',
					iconCls : 'menu-appuser',
					width : 700,
					minWidth : 700,
					height : 480,
					minHeight : 480,
					layout : 'fit',
					border : false,
					maximizable : true,
					modal : true,
					items : [panel],
					buttonAlign : 'center',
					buttons : [{
								text : '确认',
								iconCls : 'btn-ok',
								scope : this,
								handler : this.submit
							}, {
								text : '关闭',
								iconCls : 'btn-cancel',
								scope : this,
								handler : this.close
							}]
				});
		return this.win;
	},

	/**
	 * 组件初始化 isSingle：是否单选,默认单选
	 */
	initPanel : function(isSingle, selval) {
		// ///////////////contactGrid[用户列表] start///////////////////
		this.contactGrid = new KE.GridPanel({
					title : '【' + curUserInfo.depName + '】用户列表',
					region : 'center',
					height : 380,
					pageSize : 100,
					isShowTbar: false,
					singleSelect : isSingle,
					autoWidth : true,
					url : __ctxPath + '/system/selectTypeAppUser.do',
					baseParams : {
						// 是否全部，还是本单位
						'roleType' : this.roleType						
					},
					fields : ['userId', 'fullname', 'title'],
					rownumbercfg : {
						width : 40
					},
					defaults : {
						menuDisabled : true
					},
					columns : [{
						header : "姓名",
						dataIndex : 'fullname',
						width : 60,
						renderer : function(value, meta, record) {
							var title = record.data.title;
							if (title == '1') {
								return '<img src="' + __ctxPath
										+ '/images/flag/man.png"/>&nbsp;'
										+ value;
							} else {
								return '<img src="' + __ctxPath
										+ '/images/flag/women.png"/>&nbsp;'
										+ value;
							}
						}
					}]
				});
		// 单选：根据传入值，选中GridPanel
		Ext.defer(function() {
			if(isSingle && selval) {
				var model = this.contactGrid.getSelectionModel();
				this.contactGrid.getStore().each(function(rec) {
					if(rec.data.userId == selval) {
						model.select([rec]);
						return;
					}
				});
			}	
		}, 200, this);
		// ////////////////////contactGrid[用户列表] end///////////////////////
		var me = this;
		// ////////////////////selectedUserGrid[已选用户列表]
		this.selectedUserGrid = new KE.GridPanel({
					title : '已选用户',
					border : false,
					showPaging : false,
					rownumbercfg : {
						width : 40
					},
					store : new Ext.data.ArrayStore({
								fields : ['userId', 'fullname']
							}),
					columns : [{
								header : "姓名",
								dataIndex : 'fullname'
							}]
				});
		this.selectedUserGrid.on('rowdblclick', function(grid, rec) {
					var grid = me.selectedUserGrid;
					var store = grid.getStore();
					var rows = grid.getSelectionModel().getSelection();
					for (var i = 0; i < rows.length; i++) {
						store.remove(rows[i]);
					}
				});
		// ///////////////////selectedUserGrid[已选用户列表] end //////////////
		this.contactGrid.on('rowdblclick', function(grid, rec) {
					var selGrid = me.selectedUserGrid;
					var selStore = selGrid.getStore();
					var rows = me.contactGrid.getSelectionModel()
							.getSelection();
					for (var i = 0; i < rows.length; i++) {
						var userId = rows[i].data.userId;
						var fullname = rows[i].data.fullname;
						var isExist = false;
						// 查找是否存在该记录
						for (var j = 0; j < selStore.getCount(); j++) {
							if (selStore.getAt(j).data.userId == userId) {
								isExist = true;
								break;
							}
						}
						if (!isExist) {
							var newData = {
								userId : userId,
								fullname : fullname
							};
							var rec = selStore.getModel().create(newData);
							selStore.insert(selStore.getCount(), rec);
						}
					}
				});
		// 多选：根据传入值，选中GridPanel
		Ext.defer(function() {
			if(!isSingle && selval) {
				$postAjax({
					url : __ctxPath + '/system/selectedUserAppUser.do',
					params: {ids: selval},
					callback: function(json) {
						if(json.length > 0) {
							for(var i=0; i<json.length; i++) {
								var newData = {
									userId : json[i].userId,
									fullname : json[i].fullname
								};
								var selStore = me.selectedUserGrid.getStore(); 
								var rec = selStore.getModel().create(newData);
								selStore.insert(selStore.getCount(), rec);
							}
						}
					}
				});
			}	
		}, 300);
		
		// ///////////////////selectedPanel[多选面板] start/////////////////////
		// 多选添加的面板
		this.selectedPanel = new Ext.Panel({
					layout : 'border',
					region : 'east',
					width : 300,
					height : 380,
					border : false,
					items : [new Ext.Panel({
										region : 'west',
										width : 50,
										layout : {
											type : 'vbox',
											pack : 'center',
											align : 'stretch'
										},
										defaults : {
											margin : '0 5 10 5',
											xtype : 'button'
										},
										// defaultType : 'button',
										items : [{
													iconCls : 'add-all',
													text : '',
													scope : this,
													handler : this.addAll
												}, {
													iconCls : 'rem-all',
													text : '',
													scope : this,
													handler : this.removeAll
												}]
									}), {
								region : 'center',
								layout : 'fit',
								items : [this.selectedUserGrid]
							}]
				}); // selectedPanel
		// /////////////////////selectedPanel end//////////////////////////////

		var panel = new Ext.Panel({
					id : 'contactPanel',
					layout : 'border',
					anchor : '96%,96%',
					items : [this.contactGrid]
				}); // end of this contactPanel
		// 添加：多选面板
		if (isSingle != null && isSingle == false) {
			panel.add(this.selectedPanel);
			panel.doLayout();
		}
		return panel;
	}, // init

	// //////////////###方法###///////////////////////

	// 添加所有
	addAll : function() {
		var contactGrid = this.contactGrid;
		var selGrid = this.selectedUserGrid;
		var selStore = selGrid.getStore();
		var rows = contactGrid.getSelectionModel().getSelection();
		for (var i = 0; i < rows.length; i++) {
			var userId = rows[i].data.userId;
			var fullname = rows[i].data.fullname;
			var isExist = false;
			// 查找是否存在该记录
			for (var j = 0; j < selStore.getCount(); j++) {
				if (selStore.getAt(j).data.userId == userId) {
					isExist = true;
					break;
				}
			}
			if (!isExist) {
				var newData = {
					userId : userId,
					fullname : fullname
				};
				var rec = selStore.getModel().create(newData);
				selStore.insert(selStore.getCount(), rec);
			}
		}
		selGrid.getView().refresh();
	},

	// 移除所有
	removeAll : function() {
		var selGrid = this.selectedUserGrid;
		var rows = selGrid.getSelectionModel().getSelection();
		var selStore = selGrid.getStore();
		for (var i = 0; i < rows.length; i++) {
			selStore.remove(rows[i]);
		}
	},

	/**
	 * 确定，提交
	 * 
	 * @param isSingle
	 *            是否单选
	 * @param callback
	 *            回传函数
	 */
	submit : function() {
		var userIds = '';
		var fullnames = '';
		if (this.isSingle == null || this.isSingle) {// 选择单个用户
			var grid = this.contactGrid;
			var rows = grid.getSelectionModel().getSelection();

			for (var i = 0; i < rows.length; i++) {
				if (i > 0) {
					userIds += ',';
					fullnames += '，';
				}
				userIds += rows[i].data.userId;
				fullnames += rows[i].data.fullname;
			}
		} else {
			var selStore = this.selectedUserGrid.getStore();
			for (var i = 0; i < selStore.getCount(); i++) {
				if (i > 0) {
					userIds += ',';
					fullnames += '，';
				}
				userIds += selStore.getAt(i).data.userId;
				fullnames += selStore.getAt(i).data.fullname;
			}
		}

		if (this.callback != null) {
			this.callback.call(this.scope, userIds, fullnames);
		}
		this.win.close();
	},

	/**
	 * 关闭当前窗口
	 */
	close : function() {
		this.win.close();
	}
};
